package com.han.fu.api.common.handle;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.han.fu.common.utils.IdUtil;
import com.han.fu.api.common.model.UserDetail;
import com.han.fu.api.common.utils.CurrentUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 自动填充字段
 *
 * @author: star
 * @date: 2021-07-31
 */
@Slf4j
@Component
public class ApiMetaObjectHandler implements MetaObjectHandler {

    @Autowired
    private CurrentUserUtil currentUserUtil;

    /**
     * 插入自动填充
     *
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        UserDetail user = currentUserUtil.getUser();
        if (null != user) {
            this.fillStrategy(metaObject, "id", IdUtil.generate());
            this.fillStrategy(metaObject, "createUser", user.getId());
            this.fillStrategy(metaObject, "createUserName", user.getName());
        }
    }

    /**
     * 更新自动填充
     *
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        UserDetail user = currentUserUtil.getUser();
        if (null != user) {
            this.fillStrategy(metaObject, "updateUser", user.getId());
            this.fillStrategy(metaObject, "updateUserName", user.getName());
        }
    }
}
